package com.xinchengxd.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinchengxd.commons.ResponseResult;
import com.xinchengxd.gateway.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author: 姚新成
 * @Date: 2021/11/12:0:00
 * @Description: 全局过滤器
 */

@Slf4j
@Component
public class Filter implements GlobalFilter, Ordered {
    @Resource
    private UserService userService;

        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            log.info("custom global filter");
            log.debug(exchange.getAttributes().toString());
            log.debug(exchange.getApplicationContext().getApplicationName());

            /*对登录请求放行*/
            System.out.println("请求的路径是:" + exchange.getRequest().getPath().toString());
            String repath = exchange.getRequest().getPath().toString();
            if(repath.equals("/user/sign")){
                log.debug("进入user/sign");
                return chain.filter(exchange);
            }

            /*token校验*/
            HttpHeaders headers = exchange.getRequest().getHeaders();
            String token = headers.getFirst("Access-Token");
            System.out.println("str:" + token);
            ResponseResult<String> TokenRes = userService.verify(token);
            System.out.println("restoken:"+ TokenRes);

            /*对校验结果进行处理*/
            if(TokenRes.getCode()!=200){
                log.debug("tokenCode:{}",TokenRes.getCode());
                ServerHttpResponse response = exchange.getResponse();
                ObjectMapper objectMapper = new ObjectMapper();
                byte[] bytes = new byte[0];
                try {
                     bytes = objectMapper.writeValueAsString(TokenRes).getBytes(StandardCharsets.UTF_8);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                DataBuffer wrap = response.bufferFactory().wrap(bytes);
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
               /*中止请求，进行返回*/
                return response.writeWith(Mono.just(wrap));
            }
            /*设置头*/
//            exchange.getRequest().getHeaders().set("userID",TokenRes.getData());
//            exchange.getResponse().getHeaders().set("userID",TokenRes.getData());
            ServerHttpRequest userID = exchange.getRequest().mutate().header("userID", TokenRes.getData()).build();
            ServerWebExchange build = exchange.mutate().request(userID).build();

            return chain.filter(build);
        }

        @Override
        public int getOrder() {
            return -1;
        }
}
